package com.zz.hhbl.ui.setting

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.zz.framework.core.adapter.KotlinAdapter
import com.zz.framework.core.base.BaseFragment
import com.zz.framework.core.ext.dp
import com.zz.framework.core.ext.finish
import com.zz.framework.core.ext.getAppVersion
import com.zz.framework.core.ext.loadUrl
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.toast.ToastUtils
import com.zz.framework.core.utils.DeviceUtils
import com.zz.framework.core.utils.IntentBuilder
import com.zz.framework.core.utils.VersionUtils
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.framework.core.utils.language.Strings
import com.zz.hhbl.R
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.FragmentSettingBinding
import com.zz.hhbl.databinding.ItemSettingBinding
import com.zz.hhbl.entity.SettingEntity
import com.zz.hhbl.entity.SpotInfoEntity
import com.zz.hhbl.entity.VersionType
import com.zz.hhbl.event.OnLanguageSwitchEvent
import com.zz.hhbl.event.ScanResultEvent
import com.zz.hhbl.ui.CommonViewModel
import com.zz.hhbl.ui.LaunchActivity
import com.zz.hhbl.ui.SearchFragment
import com.zz.hhbl.ui.TestTranslateFragment
import com.zz.hhbl.ui.ai.AiActivity
import com.zz.hhbl.ui.earphone.EarphoneChoiceFragment
import com.zz.hhbl.ui.navigation.WalkNavigationActivity
import com.zz.hhbl.ui.translate.TranslateActivity
import com.zz.hhbl.utils.DialogUtils
import com.zz.hhbl.utils.itemdecoration.RecyclerViewDivider
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import java.io.File
import kotlin.getValue

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/5 17:50.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class SettingFragment : BaseFragment(R.layout.fragment_setting) {
    private val viewModel by viewModels<CommonViewModel>()
    var currentPosition = -1

    private val settings: MutableList<SettingEntity>
        get() {
            val list = mutableListOf<SettingEntity>()
            if (LanguageManager.currentLangCode == "zh-CN"){
                list.add(SettingEntity(Strings.AI翻译, Strings.多语实时精译, R.drawable.vector_setting_ai_translate))
            }else{
                list.add(SettingEntity(Strings.AI对话, Strings.流畅语转交流, R.mipmap.ic_setting_ai_conversation))
            }
            list.add(SettingEntity(Strings.微地图导航, Strings.精准路线规划, R.drawable.vector_setting_navigation))
            list.add(SettingEntity(Strings.连接耳机, Strings.降噪静谧聆听, R.drawable.vector_setting_connect_headphones))
            list.add(SettingEntity(Strings.切换语言, Strings.高效语言转换, R.drawable.vector_setting_switch_language))
            list.add(SettingEntity(Strings.景点查询, Strings.你身边的活地图, R.drawable.vector_setting_spot_search))
            list.add(SettingEntity(Strings.版本更新, "V ${getAppVersion()}", R.drawable.vector_setting_version_update))
            return list
        }
    lateinit var mAdapter: KotlinAdapter<SettingEntity, *>
    val binding by viewBinding<FragmentSettingBinding>()
    override fun initView() {
        super.initView()
        viewModel.initKetch()
        val mSpotInfo: SpotInfoEntity? = GlobalCache.getSpotInfo()
        mSpotInfo?.welcomeData?.firstOrNull()?.let {
            binding?.ivBackground?.loadUrl(it.url.orEmpty())
        }
        binding?.apply {
            btnBack.text = Strings.返回.toLanguage()
            btnBack.onClick {
                finish()
            }
            recyclerView.layoutManager = GridLayoutManager(requireActivity(), 2)
            recyclerView.adapter = KotlinAdapter.Builder<SettingEntity, ItemSettingBinding>(ItemSettingBinding::class.java)
                .addBindView { holder, item ->
                    run {
                        holder.binding?.apply {
                            ivIcon.setImageResource(item?.iconRes ?: R.mipmap.ic_setting_ai_conversation)
                            tvTitle.setText(item?.title.orEmpty().toLanguage())
                            tvContent.setText(item?.content.orEmpty().toLanguage())
                        }
                    }
                }.onItemClick { holder, item ->
                    run {
                        currentPosition = holder.layoutPosition
                        when (item?.title.orEmpty()) {
                            Strings.AI翻译 -> {
//                                showProgress()
//                                viewModel.getChatTokenConfig()
                                IntentBuilder.Builder().startParentActivity(this@SettingFragment, TestTranslateFragment::class.java)
                            }
                            Strings.AI对话 -> {
                                showProgress()
                                viewModel.getChatTokenConfig()
                            }
                            Strings.连接耳机 -> {
                                IntentBuilder.Builder().putExtra("isBack", true).startParentActivity(this@SettingFragment, EarphoneChoiceFragment::class.java)
                            }
                            Strings.切换语言 -> {
                                IntentBuilder.Builder().putExtra("isBack", true).setClass(requireActivity(), LaunchActivity::class.java).startActivity()
                            }
                            Strings.版本更新 -> {
                                showProgress()
                                viewModel.getVersion()
                            }
                            Strings.微地图导航 -> {
                                IntentBuilder.Builder().setClass(requireActivity(), WalkNavigationActivity::class.java).startActivity()
                            }
                            Strings.景点查询 -> {
                                startParentActivity(SearchFragment::class.java)
                            }
                        }
                    }
                }.setNewData(settings).create().also { mAdapter = it }
            recyclerView.addItemDecoration(
                RecyclerViewDivider.grid().dividerSize(15.dp())
                    .includeEdge()
                    .build()
            )
        }
    }

    override fun initObserver() {
        super.initObserver()
        viewModel.getChatTokenConfigLiveData.observe(this) {
            dismissProgress()
            if (LanguageManager.currentLangCode == "en"){
                IntentBuilder.Builder().setClass(activity, AiActivity::class.java).startActivity()
            }else{
                IntentBuilder.Builder().setClass(activity, TranslateActivity::class.java).startActivity()
            }
        }
        viewModel.versionState.observe(this) {
            dismissProgress()
            it?.forEach {
                when (it.type) {
                    //app版本
                    VersionType.APP.type -> {
                        if (VersionUtils.versionShouldUpdate(it.version, getAppVersion())) {
                            DialogUtils.showVersionUpdateDialog(requireActivity()) {
                                it.url?.let {
                                    showProgress()
                                    viewModel.downloadApk(it)
                                }
                            }
                        } else {
                            ToastUtils.show(Strings.已是最新版本.toLanguage())
                        }
                    }
                }
            }
        }
        viewModel.downloadApkSuccessLiveData.observe(this) {
            dismissProgress()
            DeviceUtils.installApk(requireActivity(), File(it))
        }
        viewModel.downloadApkFailureLiveData.observe(this) {
            dismissProgress()
            ToastUtils.show(Strings.下载失败)
        }
    }

    @Subscribe
    fun onMessage(e: OnLanguageSwitchEvent) {
        mAdapter.setNewData(settings)
        binding?.btnBack?.text = Strings.返回.toLanguage()
        val mSpotInfo: SpotInfoEntity? = GlobalCache.getSpotInfo()
        mSpotInfo?.welcomeData?.firstOrNull()?.let {
            binding?.ivBackground?.loadUrl(it.url.orEmpty())
        }
    }

    @Subscribe
    fun onMessage(e: ScanResultEvent) {
       finish()
    }

    override fun initData() {
        super.initData()
    }
}